package com.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @author Wang Chen Peng
 * @date 2018/12/24
 * describe: 处理消息的handler
 * 在netty 中 TextWebSocketFrame 是用于为websocket专门处理文本的对象 frame是消息的载体
 * @since 1.8
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 用户记录和管理所有客户端的channel
     */
    private static ChannelGroup chients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        //获取客户端传送过来的消息
        final String msg = textWebSocketFrame.text();
        System.out.println("接收到的数据 : "+msg);

        //通过 chients 可直接刷给所有连接的客户端 不用进行遍历
        /*for (Channel chient : chients) {
            chient.writeAndFlush(new TextWebSocketFrame("[时间] : "+ LocalDateTime.now()+" 消息 : "+msg));
        }*/
        chients.writeAndFlush(new TextWebSocketFrame("[时间] : "+ LocalDateTime.now()+" 消息 : "+msg));

    }

    /**
     * 当客户端连接到服务器之后
     * 获取到客户端的channel 并且放入到channelGroup中去进行管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //
        Channel channel = ctx.channel();
        chients.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当触发handlerRemoved  ChannelGroup会自动移除对应客户端的channel
        //chients.remove(ctx.channel());
        System.out.println("长id : "+ctx.channel().id().asLongText()+ " 客户端下线");
        System.out.println("短id : "+ctx.channel().id().asShortText()+ " 客户端下线");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("长id : "+ctx.channel().id().asLongText()+ " 客户端连接成功");
        System.out.println("短id : "+ctx.channel().id().asShortText()+ " 客户端连接成功");
    }
}
